<?php

function template($f,$viewdir = false)
{
	global $_debug;
	$_template = new QuickSkin($f);
	$_template->set( 'reuse_code', !$_debug );
	$_template->set( 'extensions_dir', 'library/quickskin_extensions/' );
	if ($viewdir)
	{
		$_template->set( 'template_dir', $viewdir );
	}
	else
	{
		$_template->set( 'template_dir', LZ_VIEWER_DIR );
	}
	$_template->set( 'temp_dir', 'cache/template/' );
	$_template->set( 'cache_dir', 'cache/' );
	//$_template->set( 'cache_lifetime', 200 );
	return $_template;
}


/*
register this page to be cached
*/
function cache_this_page($t = 120)
{
	define('LZ_CACHE_VIEW','yes');
	define('LZ_CACHE_TTL',$t);
}


function lz_exit($content,$url,$t = 2)
{
	$temp = template('exit.html');
	$temp->assign( array
	(
		'content' => $content,
		'url' => $url,
		'time' => $t,
	));
	$temp->output();
	die;
}

function array_add(&$arr1,$arr2,$assoc = true)
{
	foreach($arr2 as $key=>$val)
	{
		if ($assoc)
			$arr1[$key] = $val;
		else
			$arr1[] = $val;
	}
}

function lz_encode($s)
{
	if (!$s) return '';
	$s = md5($s).$s.'something very very very very very very very very long';
	return sha1($s);
}


function filter_array($arr,$keys,$write_global = false)
{
	$re = array();
	$key_arr = explode(',',$keys);
	foreach($key_arr as $key)
	{
		$key = trim($key);
		if (!$key) continue;
		$_must = false;
		$_func = false;
		$_key = false;
		if (strpos($key,'=') !== false)
		{
			$_arr = explode('=',$key);
			$_key = $_arr[0];
			$key = $_arr[1];
		}
		if (strpos($key,'!') !== false)
		{
			$_must = true;
			$key = str_replace('!','',$key);
		}
		if (strpos($key,':') !== false)
		{
			$_arr = explode(':',$key);
			$_func = $_arr[0];
			$key = $_arr[1];
		}
		!$_key && $_key = $key;
		if ($_func && function_exists($_func))
			if (eval('$arr[$key] = '.$_func.'($arr[$key]);') === false) return false;
		if ($_must && !$arr[$key]) 
			return false;
		else
			$re[$_key] = $arr[$key];
	}
	if ($write_global)
	{
		foreach($re as $key => $val)
		{
			$GLOBALS[$key] = $val;
		}
	}
	return $re;
}

function page_content($s,$url,$backurl)
{
	global $config;
	if (!$config['item_page_size']) $config['item_page_size'] = 500;
	$page = $_GET['page'];
	if ($page == 'all')
	{
		return nl2br($s).'<br /><a href="'.$backurl.'">'.PAGE_RETURN.'</a>';
	}
	else
		$page = intval($page);
	
	!$page && $page=1;
	$per_page = intval($config['item_page_size']);
	$total_length = mb_strlen($s,'UTF-8');
	$total_page = ceil($total_length/$per_page);
	$page>$total_page && $page = $total_page;
	$s = cn_substr($s,($page-1)*$per_page,$per_page);
	
	if ($total_page>1)
	{
		$s = '('.$page.'/'.$total_page.' <a href="'.$url.'&amp;page=all">'.PAGE_ALL.'</a>)<br />'.$s;
	}
	
	$pager = ($page >= $total_page)?'<br /><a href="'.$backurl.'">'.PAGE_RETURN.'</a><br />':'<br />';
	$pager.= get_pager($url,$total_page,$page);
	return nl2br($s).$pager;
}

function get_pager($url,$total_page,$page = 1)
{
	$pager = '';
	if ($page<$total_page)
		$pager.= '<a href="'.$url.'&amp;page='.($page+1).'">'.PAGE_NEXT.'</a><br />';
		
	if ($total_page>1)
	{
		for($i=1;$i<=$total_page;$i++)
		{
			if ($page == $i)
				$pager.= "[$i] ";
			else
				$pager.= '<a href="'.$url.'&amp;page='.$i.'">'.$i.'</a> ';
		}
	}
	return $pager;
}

function html_pager($url,$total_page,$page = 1)
{
	$page_span = 4;
	$pager = '';
	if ($total_page == 1) return '';
	if ($page>2)
		$pager .= ' <a href="'.$url.'&page=1">'.PAGER_FIRST.'</a> ';
	if ($page>1)
		$pager.= ' <a href="'.$url.'&page='.($page-1).'">'.PAGER_PREV.'</a> ';
	
	if ($page>$page_span)
		$pager.= '...';
	
	for($i=$page-$page_span+1;$i<$page+$page_span;$i++)
	{
		if ($i<=0 || $i>$total_page) continue;
		if ($page == $i)
			$pager.= " [{$i}] ";
		else
			$pager.= ' <a href="'.$url.'&page='.$i.'">'.$i.'</a> ';
	}
	
	if ($total_page-$page>$page_span)
		$pager.= '...';
	
	
	if ($page<$total_page)
		$pager.= ' <a href="'.$url.'&page='.($page+1).'">'.PAGER_NEXT.'</a> ';
	if ($page+1<$total_page)
		$pager .= ' <a href="'.$url.'&page='.$total_page.'">'.PAGER_LAST.'</a> ';
	return $pager;
}

function cn_substr($str, $start, $len)
{
	$tmpstr = "";
	$strlen = strlen($str);
	$cnt = 0;
	$istr = '';
	for($i = 0; $i < $strlen; $i++) 
	{
        if(ord(substr($str, $i, 1)) > 127) 
		{
            $istr = substr($str, $i, 3);
            $i+=2;
        }
		else
		{
            $istr = substr($str, $i, 1);
		}
		if ( $cnt >= $start && $cnt < $start+$len)
		{
			$tmpstr .= $istr;
		}
		$cnt++;
    }
    return $tmpstr;
}

function format_date($t)
{
	return date('Y-m-d H:i',$t);
}
function get_format_date($t)
{
	if (date('Y',$t) != date('Y'))
	{
		$re = date('Y'.EVENT_YEAR.'m'.EVENT_MONTH.'d'.EVENT_DAY,$t);
	}
	else if (date('m',$t) != date('m'))
	{
		$re = date('m'.EVENT_MONTH.'d'.EVENT_DAY,$t);
	}
	else if (date('d',$t) != date('d'))
	{
		switch( date('d',$t) - date('d') )
		{
			case 2:
				$re = TDAT;
				break;
			case 1:
				$re = TOMOROW;
				break;
			case -1:
				$re = YESTODAY;
				break;
			default:
				$re = date('d'.EVENT_DAY,$t);
		}
	}
	else
	{
		$re = TODAY;
	}
	switch(strtolower(date('D',$t)))
	{
		case 'sun':
			$w = SUNDAY;
			break;
		case 'mon':
			$w = MONDAY;
			break;
		case 'tue':
			$w = TUESDAY;
			break;
		case 'wed':
			$w = WEDNESDAY;
			break;
		case 'thu':
			$w = THURSDAY;
			break;
		case 'fri':
			$w = FRIDAY;
			break;
		case 'sat':
			$w = SATURDAY;
			break;
		default:
			$w = '';
	}
	
	$re .= ($re != TODAY )?'('.$w.')':'';
	$re .= date('H:i',$t);
	return $re;
}


function if_allowed($action)
{
	if ($_SESSION['login_user']['name'] == 'Administrator' || $_SESSION['login_user']['rights'] == 'all')
	{
		return true;
	}
	else
	{
		return (strpos(','.$_SESSION['login_user']['rights'].',',','.$action.',') !== false);
	}
}

function lz_base64_encode($s)
{
	return str_replace(array('+','/','='),array('plus','slash','equal'),base64_encode($s));
}
function string2words($s,$return_string = true,$encode64 = true,$simple_split = false)
{
	$re = '';
	if (preg_match_all("/([\x{4e00}-\x{9fff}]{2,})/u",$s,$ms))
	{
		foreach($ms[0] as $w)
		{
			if ($simple_split)
			{
				$re.=" ".$w;
			}
			else
			{
				$l = strlen($w)/3;
				for($i=0;$i<$l;$i++)
				{
					$wi = substr($w,$i*3,6);
					if (strlen($wi) > 3)
					{
						$re .= ($encode64)?' '.lz_base64_encode($wi):' '.$wi;
					}
				}
			}
		}
	}
	if (preg_match_all("/(\d+[.]?\d+)/",$s,$ms))
	{
		foreach($ms[0] as $wi)
		{
			if(strlen($wi) >= 2)
			{
				$re .= ($encode64)?' '.lz_base64_encode($wi):' '.$wi;
			}
		}
		$s = preg_replace("/(\d+[.]?\d+)/",' ',$s);
	}
	$s = preg_replace("/([^\x{00}-\x{ff}]+)/u",' ',$s);
	$re = $s.' '.$re;
	if (!$return_string)
	{
		$re = preg_replace("/([^\d])([,.\-\?\n])([^\d])/",'$1 $3',$re);
		$re = trim(preg_replace("/[\s]{2,}/",' ',$re));
		$arr = explode(' ',$re);
		$re = array();
		foreach($arr as $a)
		{
			if (strlen($a) >= 2) $re[] = $a;
		}
		return $re;
	}
	else
	{
		$re = trim(preg_replace("/[\s,\.]{2,}/",' ',$re));
		return $re;
	}
}

if (!function_exists('json_encode'))
{
	function json_encode($arr)
	{
		$keys = array_keys($arr);
		$isarr = true;
		$json = "";
		for($i=0;$i<count($keys);$i++)
		{
			if ($keys[$i] !== $i)
			{
				$isarr = false;
				break;
			}
		}
		$json = $space;
		$json.= ($isarr)?"[":"{";
		for($i=0;$i<count($keys);$i++)
		{
			if ($i!=0) $json.= ",";
			$item = $arr[$keys[$i]];
			$json.=($isarr)?"":'"'.$keys[$i].'":';
			if (is_array($item))
				$json.=json_encode($item);
			else if (is_string($item))
				$json.='"'.str_replace(array("\r","\n"),array('\r','\n'),$item).'"';
			else if (!$item) $json.='null';
			else $json.=$item;
		}
		$json.= ($isarr)?"]":"}";
		return $json;
	}
}

/*
send download header and output filedata
*/
function download_file($filepath, $filename = '')
{
	if(!$filename) $filename = basename($filepath);
	$filetype = get_ext($filepath);
	if (strpos(strtolower($filename),'.'.$filetype) === false) $filename .= '.'.$filetype;
	if(!is_mac_os()) $filename = iconv('UTF-8','GB2312',$filename);
	$filesize = sprintf("%u", filesize($filepath));
	if(@ob_get_length() !== false) @ob_end_clean();
	header('Pragma: public');
	header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
	header('Cache-Control: no-store, no-cache, must-revalidate');
	header('Cache-Control: pre-check=0, post-check=0, max-age=0');
	header('Content-Transfer-Encoding: binary');
	header('Content-Encoding: none');
	header('Content-type: application/x-octet-stream');
	header('Content-Disposition: attachment; filename="'.$filename.'"');
	header('Content-length: '.$filesize);
	readfile($filepath);
	exit;
}

/*
if the client browser is IE
*/
function is_ie()
{
	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
	if(strpos($useragent, 'msie ') !== false) return true;
	return false;
}

function is_windows()
{
	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if(strpos($useragent, 'windows')) return true;
	return false;
}

function is_mac_os()
{
	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if(strpos($useragent, 'mac os')) return true;
	return false;
}
/*
get file extension
*/
function get_ext($s)
{
	if (!$s) return '';
	$arr = explode('.',$s);
	if (count($arr) <= 1) return '';
	return strtolower($arr[count($arr)-1]);
}

?>